<template>
	<div class="bg-white rounded-lg shadow-md p-6">
		<el-table ref="tableRef" :data="currentData" border @selection-change="handleSelectionChange"
			@select="handleSelect" @select-all="handleSelectAll" style="width: 100%">
			<el-table-column type="selection" width="55"></el-table-column>
			<el-table-column prop="id" label="ID" width="100"></el-table-column>
			<el-table-column prop="name" label="姓名" width="120"></el-table-column>
			<el-table-column prop="age" label="年龄" width="80"></el-table-column>
			<el-table-column prop="address" label="地址"></el-table-column>
		</el-table>

		<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
			:page-sizes="[5, 10, 20]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
			:total="total">
		</el-pagination>

		<div class="text-sm text-gray-600">
			当前已选择 <span class="font-medium text-primary">{{ selectedCount }}</span> 条数据，
			最大可选择 <span class="font-medium text-primary">{{ maxSelectCount }}</span> 条数据
		</div>
	</div>
</template>

<script>
export default {
	name: 'UserTable',
	data() {
		return {
			allData: [],
			currentData: [],
			currentPage: 1,
			pageSize: 5,
			total: 0,
			selectedIds: new Set(),
			maxSelectCount: 8
		}
	},
	computed: {
		selectedCount() {
			return this.selectedIds.size;
		},
		isMaxSelected() {
			return this.selectedCount >= this.maxSelectCount;
		}
	},
	mounted() {
		this.initData();
	},
	methods: {
		initData() {
			this.allData = Array.from({ length: 100 }, (_, i) => ({
				id: i + 1,
				name: `用户${i + 1}`,
				age: Math.floor(Math.random() * 50) + 18,
				address: `城市${Math.floor(Math.random() * 10) + 1}区${Math.floor(Math.random() * 100) + 1}号`
			}));
			this.total = this.allData.length;
			this.loadPageData();
		},
		// 加载当前页数据
		loadPageData() {
			const start = (this.currentPage - 1) * this.pageSize;
			const end = start + this.pageSize;
			// 确保不会超出数据范围
			this.currentData = this.allData.slice(start, end);
			this.$nextTick(() => {
				this.setCurrentPageSelection();
			});
		},
		setCurrentPageSelection() {
			this.$refs.tableRef.clearSelection();
			if (this.selectedIds.size === 0) return;

			this.currentData.forEach(row => {
				if (this.selectedIds.has(row.id)) {
					this.$refs.tableRef.toggleRowSelection(row, true);
				}
			});
		},
		handleSelect(selection, row) {
			// 计算当前选择状态下的数量
			const wouldBeSelected = new Set(this.selectedIds)
			if (wouldBeSelected.has(row.id)) {
				wouldBeSelected.delete(row.id); // 取消选择
			} else {
				wouldBeSelected.add(row.id); // 添加选择
			}

			// 如果添加选择后超过最大数量，阻止并提示
			if (wouldBeSelected.size > this.maxSelectCount) {
				this.$message.warning(`最多只能选择${this.maxSelectCount}条数据`);
				this.$refs.tableRef.toggleRowSelection(row, false);
				return;
			}

			// 更新实际选择状态
			this.selectedIds = wouldBeSelected;
		},
		handleSelectAll(selection) {
			// 初始化进入页面，没有勾选状态，默认Ids是空的，所以已选条数为0
			this.selectedIds = new Set(this.selectedIds)
			// console.log(this.selectedIds, 'xuanzhongdeiddddddddddd');
			if (this.currentData.length === 0) return;

			// 清除所有已选状态
			this.selectedIds.clear();
			this.$refs.tableRef.clearSelection();
			// 如果当前页数据少于最大选择数量，直接选择所有 
			// Math.min()以上会出现的问题,如果当前当前页数据少于最大选择数量，会少选。加入我想一下选10个，当前页面只有5个数据，应该选5个，第二个页面继续选5个
			const availableCount = Math.min(this.maxSelectCount, this.currentData.length);
			// 选择前availableCount条数据 
			const selectedRows = this.currentData.slice(0, availableCount);
			
			selectedRows.forEach(row => {
				this.$refs.tableRef.toggleRowSelection(row, true);
				this.selectedIds.add(row.id);
			});

			if (availableCount < this.currentData.length) {
				this.$message.warning(`最多只能选择${this.maxSelectCount}条数据，已自动选择前${availableCount}条`);
			}
		},
		handleSelectionChange(selection) {
			// 该方法会在单选、全选、取消选择等操作时触发
			// 由于我们在单选和全选时已经处理了selectedIds，这里不需要额外处理
		},
		handleSizeChange(newSize) {
			this.pageSize = newSize;
			this.currentPage = 1;
			this.loadPageData();
			console.log(this.selectedIds, 'meiyetiaoshu');

		},
		handleCurrentChange(newPage) {
			this.currentPage = newPage;
			this.loadPageData();
			console.log(this.selectedIds, 'dangqianye')
		}
	}
}
</script>

<style scoped>
/* 可以添加局部样式 */
</style>